package com.jic.manager.impl;

import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.mapper.CmsPageMapper;
import com.jic.manager.entity.CmsModule;
import com.jic.manager.entity.CmsModuleData;
import com.jic.manager.entity.CmsModuleTemplate;
import com.jic.manager.entity.CmsPage;
import com.jic.manager.entity.CmsTpage;
import com.jic.manager.entity.vo.request.CmsPageRequest;
import com.jic.manager.entity.vo.response.CmsPageResponse;
import com.jic.conf.request.AddCmsPageRequest;
import com.jic.manager.service.CmsModuleDataService;
import com.jic.manager.service.CmsModuleService;
import com.jic.manager.service.CmsModuleTemplateService;
import com.jic.manager.service.CmsPageService;
import com.jic.manager.service.CmsTpageService;
import com.jic.manager.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 页面信息表
 * 
 * @author :
 * @email :
 * @since : 2020-03-05 12:00:37
 * @version : v1.0.0
 */
@Service
@Slf4j

public class CmsPageServiceImpl implements CmsPageService {

	@Resource
	private CmsPageMapper cmsPageMapper;

	@Resource
	private CmsModuleService cmsModuleService;

	@Resource
	private CmsModuleTemplateService cmsModuleTemplateService;

	@Resource
	private CmsModuleDataService cmsModuleDataService;
	
	@Resource
	private CmsTpageService cmsTpageService;

	@Override
	public long insert(CmsPage cmsPage) {
		long flag = cmsPageMapper.insert(cmsPage);
		return flag;
	}

	@Override
	public long delete(Long id) {
		return cmsPageMapper.delete(id);
	}

	@Override
	public long update(CmsPage cmsPage) {
		return cmsPageMapper.update(cmsPage);
	}

	@Override
	public CmsPage queryByPrimaryKey(Long id) {
		return cmsPageMapper.queryByPrimaryKey(id);
	}

	@Override
	public List<CmsPage> query(CmsPage cmsPage) {
		return cmsPageMapper.query(cmsPage);
	}

	@Override
	public PageResult<CmsPage> queryPage(CmsPage cmsPage, Page pageQuery) {
		// 计算下标
		int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
		List<CmsPage> list = cmsPageMapper.queryPage(startIndex, pageQuery.getLimit(), cmsPage);
		long count = cmsPageMapper.queryPageCount(cmsPage);
		PageResult pageResult = new PageResult();
		pageResult.setRows(list);
		pageResult.setTotal(count);
		return pageResult;
	}

	@Override
	public long lowerCmspage(Long id) {

		return cmsPageMapper.lowerCmspage(id);
	}

	@Override
	public PageResult<CmsPage> queryPages(CmsPage cmsPage, Page pageQuery) {
		// 计算下标
		int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
		List<CmsPage> list = cmsPageMapper.queryPages(startIndex, pageQuery.getLimit(), cmsPage);
		long count = cmsPageMapper.queryPagesCount(cmsPage);
		PageResult pageResult = new PageResult();
		pageResult.setRows(list);
		pageResult.setTotal(count);
		return pageResult;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void copyCmsPage(Long id) {

		// 根据Id查处所有关联的数据进行复制
		CmsPage cmsPage = cmsPageMapper.queryByPrimaryKey(id);
		if (cmsPage != null) {
			CmsModule cmsModule = new CmsModule();
			cmsModule.setCmsPageId(id);
			cmsModule.setDeleteFlag(0);
			// 普通页面
			cmsModule.setRefType(0);
			// 查询页面更下的所有栏目
			List<CmsModule> cmsModules = cmsModuleService.query(cmsModule);

			if (CollectionUtils.isNotEmpty(cmsModules)) {

				Map<Long, List<CmsModuleData>> cmsModuleDataMap = new HashMap<>();

				Map<Long, CmsModuleTemplate> cmsModuleTemplateMap = new HashMap<>();

				List<Long> cmsModelIds = new ArrayList<>();

				for (CmsModule bean : cmsModules) {
					cmsModelIds.add(bean.getId());
				}

				// 查询栏目下的所有
				List<CmsModuleData> cmsModuleDatas = cmsModuleDataService.queryByModuleIds(cmsModelIds);

				if (CollectionUtils.isNotEmpty(cmsModuleDatas)) {
					for (CmsModuleData entity : cmsModuleDatas) {

						List<CmsModuleData> lst = cmsModuleDataMap.get(entity.getCmsModuleId());
						if (lst == null) {
							lst = new ArrayList<>();
							lst.add(entity);
						} else {
							lst.add(entity);
						}

						cmsModuleDataMap.put(entity.getCmsModuleId(), lst);
					}
				}

				List<CmsModuleTemplate> cmsModuleTemplates = cmsModuleTemplateService.queryByModuleIds(cmsModelIds);

				if (CollectionUtils.isNotEmpty(cmsModuleTemplates)) {
					// 因为是1对1关系，不需要判断直接放入map
					for (CmsModuleTemplate entity : cmsModuleTemplates) {
						cmsModuleTemplateMap.put(entity.getCmsModuleId(), entity);
					}
				}
				// 将普通页面关联数据同时插入
				cmsPage.setId(null);
				cmsPage.setStatus(0);
				cmsPage.setCreateTime(new Date());
				cmsPage.setUpdateTime(new Date());
				cmsPageMapper.insert(cmsPage);
				for (CmsModule cmsModel : cmsModules) {
					Long oldId = cmsModel.getId();
					cmsModel.setId(null);
					cmsModel.setCmsPageId(cmsPage.getId());
					cmsModuleService.insert(cmsModel);

					CmsModuleTemplate cmsModuleTemplate = cmsModuleTemplateMap.get(oldId);
					if (cmsModuleTemplate != null) {
						cmsModuleTemplate.setId(null);
						cmsModuleTemplate.setCmsModuleId(cmsModel.getId());
						cmsModuleTemplateService.insert(cmsModuleTemplate);
					}
					List<CmsModuleData> cmsModuleDataList = cmsModuleDataMap.get(oldId);
					if (CollectionUtils.isNotEmpty(cmsModuleDataList)) {
						for (CmsModuleData entity : cmsModuleDataList) {
							entity.setId(null);
							entity.setCmsModuleId(cmsModel.getId());
							cmsModuleDataService.insert(entity);
						}

					}

				}

			}else{
				cmsPage.setId(null);
				cmsPage.setStatus(0);
				cmsPage.setCreateTime(new Date());
				cmsPage.setUpdateTime(new Date());
				cmsPageMapper.insert(cmsPage);
			}

		}

	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long useCmsPage(Long id) {

		Long cmsPageId = null;
		// 根据Id查处所有关联的数据进行复制
		CmsTpage cmsTpage = cmsTpageService.queryByPrimaryKey(id);
		if (cmsTpage != null) {
			
			
			CmsPage cmsPage = BeanUtil.copy(cmsTpage, CmsPage.class);
			cmsPage.setTitle(cmsTpage.getName());
			cmsPage.setStatus(0);
			cmsPage.setCreateTime(new Date());
			cmsPage.setUpdateTime(new Date());
			CmsModule cmsModule = new CmsModule();
			cmsModule.setCmsPageId(id);
			cmsModule.setDeleteFlag(0);
			// 模版页面
			cmsModule.setRefType(1);
			// 查询页面更下的所有栏目
			List<CmsModule> cmsModules = cmsModuleService.query(cmsModule);

			if (CollectionUtils.isNotEmpty(cmsModules)) {

				Map<Long, List<CmsModuleData>> cmsModuleDataMap = new HashMap<>();

				Map<Long, CmsModuleTemplate> cmsModuleTemplateMap = new HashMap<>();

				List<Long> cmsModelIds = new ArrayList<>();

				for (CmsModule bean : cmsModules) {
					cmsModelIds.add(bean.getId());
				}

				// 查询栏目下的所有
				List<CmsModuleData> cmsModuleDatas = cmsModuleDataService.queryByModuleIds(cmsModelIds);

				if (CollectionUtils.isNotEmpty(cmsModuleDatas)) {
					for (CmsModuleData entity : cmsModuleDatas) {

						List<CmsModuleData> lst = cmsModuleDataMap.get(entity.getCmsModuleId());
						if (lst == null) {
							lst = new ArrayList<>();
							lst.add(entity);
						} else {
							lst.add(entity);
						}

						cmsModuleDataMap.put(entity.getCmsModuleId(), lst);
					}
				}

				List<CmsModuleTemplate> cmsModuleTemplates = cmsModuleTemplateService.queryByModuleIds(cmsModelIds);

				if (CollectionUtils.isNotEmpty(cmsModuleTemplates)) {
					// 因为是1对1关系，不需要判断直接放入map
					for (CmsModuleTemplate entity : cmsModuleTemplates) {
						cmsModuleTemplateMap.put(entity.getCmsModuleId(), entity);
					}
				}
				// 将普通页面关联数据同时插入
				cmsPage.setId(null);
				cmsPageMapper.insert(cmsPage);
				
				cmsPageId = cmsPage.getId();
				for (CmsModule cmsModel : cmsModules) {
					Long oldId = cmsModel.getId();
					cmsModel.setId(null);
					cmsModel.setCmsPageId(cmsPage.getId());
					cmsModuleService.insert(cmsModel);
					
					

					CmsModuleTemplate cmsModuleTemplate = cmsModuleTemplateMap.get(oldId);
					if (cmsModuleTemplate != null) {
						cmsModuleTemplate.setId(null);
						cmsModuleTemplate.setCmsModuleId(cmsModel.getId());
						cmsModuleTemplateService.insert(cmsModuleTemplate);
					}
					List<CmsModuleData> cmsModuleDataList = cmsModuleDataMap.get(oldId);
					if (CollectionUtils.isNotEmpty(cmsModuleDataList)) {
						for (CmsModuleData entity : cmsModuleDataList) {
							entity.setId(null);
							entity.setCmsModuleId(cmsModel.getId());
							cmsModuleDataService.insert(entity);
						}

					}

				}

			}

		}

		return cmsPageId;
	}

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@Override
	public List<CmsPageResponse> listCmsPageRecordPagination(CmsPageRequest request) {
		//分页处理
		CmsPage param = new CmsPage();
		BeanUtils.copyProperties(request, param);
		param.setDeleteFlag(0);
		List<CmsPage> list = cmsPageMapper.listCmsPageRecordPagination(request.getStart(), request.getLimit(), param);

		long count = cmsPageMapper.listPageCount(param);

		List<CmsPageResponse> schoolResponseList = list.stream().map(temp -> {
			CmsPageResponse schoolResponse = new CmsPageResponse();
			BeanUtils.copyProperties(temp, schoolResponse);
			return schoolResponse;
		}).filter(item -> item != null).collect(Collectors.toList());

		PageResult<CmsPageResponse> pageResult = new PageResult<>();
		pageResult.setRows(schoolResponseList);
		pageResult.setTotal(count);

		return new ArrayList<>();
	}

	/**
	 * 分页查询，获取总记录
	 *
	 * @param request
	 * @return
	 */
	@Override
	public long listPageCount(CmsPage request) {
		return cmsPageMapper.listPageCount(request);
	}


	/**
	 * 不分页查询
	 *
	 * @param request
	 * @return
	 */
	@Override
	public List<CmsPage> listCmsPageAllRecord(CmsPage request) {
		//分页处理
		request.setDeleteFlag(0);
		return cmsPageMapper.selectBySelective(request);
	}

	/**
	 * 修改审核
	 *
	 * @param request
	 * @return
	 */
	@Override
	public long updateCmsPage(CmsPage request) throws Throwable {
		try {
			log.info("修改记录");
			CmsPage school = new CmsPage();
			BeanUtils.copyProperties(request, school);
			long flag = cmsPageMapper.updateByPrimaryKey(school);
		} catch (Exception e) {
			log.error("记录审核失败", e);
			throw new Exception("记录修改异常");
		}

		return -1;
	}

	/**
	 * 记录详情
	 *
	 * @param request
	 * @return
	 */
	@Override
	public CmsPage getCmsPage(CmsPage request) {
		return cmsPageMapper.selectByPrimaryKey(request);
	}


	/**
	 * 新增记录
	 *
	 * @param request
	 * @return
	 */
	@Override
	public long addCmsPage(CmsPage request) {
		return cmsPageMapper.insert(request);
	}


	/**
	 * 删除记录
	 *
	 * @param request
	 * @return
	 */
	@Override
	public long deleteCmsPage(CmsPage request) {
		return cmsPageMapper.deleteByPrimaryKey(request);
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request
	 * @return
	 */
	@Override
	public long deleteCmsPageLogically(CmsPage request) {
		request.setDeleteFlag(1);
		return cmsPageMapper.updateByPrimaryKey(request);
	}

	@Override
	public RestResult<String> addPage(AddCmsPageRequest addCmsModuleRequest) {
		try {
			CmsPage cmsPage = cmsPageMapper.queryByPrimaryKey(addCmsModuleRequest.getPageId());
			if (1 == cmsPage.getDeleteFlag()){
				return RestResult.error("9999","页面不存在");
			}
			cmsPage.setId(cmsPage.getId());
			cmsPage.setTitle(addCmsModuleRequest.getTitle());
			cmsPage.setUpdateTime(new Date());
			cmsPageMapper.insert(cmsPage);
			return RestResult.success("成功");
		}catch (Exception e){
			log.error("保存页面错误--><>>>{}",e.getLocalizedMessage());
			return RestResult.error("9999","服务器错误...");
		}
	}

    @Override
    public long updateSoldOut(CmsPage cmsPage) {

            return cmsPageMapper.updateSoldOut(cmsPage);

    }


    /**
	 * 保存或修改记录信息
	 * @param request 入参实体类
	 * @return String
	 * author tzc
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	public long saveOrUpdateCmsPage(CmsPage request) throws Throwable {
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		try {
			if (request == null) {
				throw new Exception("入参为空");
			}
			//if (StringUtils.isBlank(request.getInstitutionCode())) {
			//return RestResult.error(ChoiceCenterErrorCode.EXCEPTION, "营业执照为空");
			//}
			request.setDeleteFlag(0);
			request.setCreator(request.getCreator());
			if (request.getId() != null) {
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
				return  cmsPageMapper.updateByPrimaryKey(request);
			}else{
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
				return cmsPageMapper.insertSelective(request);
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw  new Exception("记录修改异常");
		}
	}


}